package core.testes.codeGeneration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import junit.framework.TestCase;
import core.codeGeneration.CodeGenerator;
import core.error.ErrorHandler;
import core.lexical.LexicalAnalyser;
import core.syntatic.SyntaticAnalyser;

public class CodeGenerationTest extends TestCase {
	
	private SyntaticAnalyser parser;
	
	private final String fileName = "examples\\codeGenerationTest.ford";
	
	private final String codeGeneratedFile = "codeFiles\\codeGenerationTest Intermediary Code.txt";
	
	private final String tabLabelFile = "codeFiles\\codeGenerationTest Tab Label.txt";

	private BufferedReader bufReader;

	private FileReader reader;

	private FileReader tabLabelReader;

	private BufferedReader tabLabelBufReader;
	
	@Override
	protected void setUp() throws Exception {
				
		FileReader source = new FileReader( new File( fileName ) );
		
		 parser = new SyntaticAnalyser(	new LexicalAnalyser( source, new ErrorHandler() ) );
		 CodeGenerator.getInstace().init(fileName.substring(9, fileName.length() - 5));
	}
	
	@Override
	protected void tearDown() throws Exception {
		reader.close();
		bufReader.close();
		tabLabelReader.close();
		tabLabelBufReader.close();
		super.tearDown();
	}
	
	public void testCodeGeneration(){
		parser.analyseIt();
		 
		try {
			reader = new FileReader(new File(codeGeneratedFile));
			
			bufReader = new BufferedReader(reader);
			
			assertEquals(bufReader.readLine(), "1.	[ x = 15 ]");
			assertEquals(bufReader.readLine(), "2.	[ y = 7 ]");
			assertEquals(bufReader.readLine(), "3.	[ a = 5 ]");
			assertEquals(bufReader.readLine(), "4.	[ b = 9 ]");
			assertEquals(bufReader.readLine(), "5.	[ == a 5 ]");
			assertEquals(bufReader.readLine(), "6.	[ L2 jif ]");
			assertEquals(bufReader.readLine(), "7.	[ < x y ]");
			assertEquals(bufReader.readLine(), "8.	[ L3 jif ]");
			assertEquals(bufReader.readLine(), "9.	[ d[5] = 10 ]");
			assertEquals(bufReader.readLine(), "10.	[ L4 jmp ]");
			assertEquals(bufReader.readLine(), "11.	[ T1 -U b ]");
			assertEquals(bufReader.readLine(), "12.	[ T2 * 2 T1 ]");
			assertEquals(bufReader.readLine(), "13.	[ x = T2 ]");
			assertEquals(bufReader.readLine(), "14.	[ L1 jmp ]");

			tabLabelReader = new FileReader(new File(tabLabelFile));
			
			tabLabelBufReader = new BufferedReader(tabLabelReader);
			
			tabLabelBufReader.readLine();
			
			assertEquals(tabLabelBufReader.readLine(), "L1	5");
			assertEquals(tabLabelBufReader.readLine(), "L3	11");
			assertEquals(tabLabelBufReader.readLine(), "L4	14");
			assertEquals(tabLabelBufReader.readLine(), "L2	15");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 
		
	}

}
